<template>
  <div class="option-result">
    <div class="option-header">
      <div class="option-header-content"><span>计算结果</span></div>
      <div class="option-result-right-button">

<!--        <el-icon @click="exportSimpleTxtFile" title="简明式导出">
          <document-remove/>
        </el-icon>
        &nbsp;|
        <el-icon class="export" @click="exportTxtFile" title="详细式导出">
          <document/>
        </el-icon>-->
        <el-dialog v-model="dialogVisible"  width="45%" :close-on-click-modal="false" destroy-on-close draggable>
          <el-tabs v-model="activeName"  class="demo-tabs" >
            <el-tab-pane label="详细式" name="first">
              <el-input :model-value="exportTxtFile()" :rows="20" type="textarea" />
            </el-tab-pane>
            <el-tab-pane label="简略式" name="second">
              <el-input :model-value="exportSimpleTxtFile()" :rows="20" type="textarea" />
            </el-tab-pane>
          </el-tabs>
          <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
          </template>
        </el-dialog>
        <div v-if="proxy.$attrs.hasExport">
          <el-icon class="export" @click="openTxtDialog"  title="文本导出">
            <document/>
          </el-icon>
          &nbsp;|
          <el-icon @click="exportImage" title="导出图片">
            <picture-filled/>
          </el-icon>
        </div>
      </div>
    </div>
  </div>
  <div>
    <div class="optionst04" ref="resultRef">
      <el-descriptions :column="data.column" border>
        <el-descriptions-item label="npv" label-align="right" align="right">
          <template #default>
            <InputAmount v-model:value="data.newNpv" v-if="calcMarketNpv" :clearable="false"
                         precision="2"></InputAmount>
            <span v-if="!calcMarketNpv">{{ formartFormP2WithUseGrouping(data.newNpv, 2) }}</span>
          </template>

        </el-descriptions-item>
        <el-descriptions-item label-align="right" align="right">
          <template #label>
            <el-switch v-model="data.showSwitch" inline-prompt width="35"
                       active-color="#13ce66"
                       inactive-color="#e9e9eb"
                       active-text="年"
                       inactive-text="None"/>&nbsp;npv%
          </template>
          <template #default>
            <div v-if="calcInvert">
              <InputAmount v-show="!data.showSwitch" v-model="data.npvPercentage"  :clearable="false" @blur="()=>{
                if(!data.showSwitch){
                      data.newNpv = CalcNpvByNpvPercent(proxy.$attrs.form, data.npvPercentage,false)
                      data.yearnpvPercentage = CalcNpvPercentByNpv(proxy.$attrs.form, data.newNpv, false)
                }
              }"
                           precision="4"></InputAmount>
              <InputAmount v-show="data.showSwitch" v-model="data.yearnpvPercentage"  :clearable="false" @blur="()=>{
                if(data.showSwitch){
                     data.newNpv = CalcNpvByNpvPercent(proxy.$attrs.form, data.yearnpvPercentage,true)
                     data.npvPercentage = CalcNpvPercentByNpv(proxy.$attrs.form, data.newNpv, true)
                }
              }"
                           precision="4"></InputAmount>
            </div>

            <div v-if="!calcInvert">
              <div v-show="!data.showSwitch">{{ formartFormP4(props.result['npvPercentage']) }}</div>
              <div v-show="data.showSwitch">{{ formartFormP4(props.result['yearnpvPercentage']) }}</div>
            </div>
          </template>
          <!--{{ formartFormP2(props.result["npv%"]) }}-->
        </el-descriptions-item>
        <el-descriptions-item label="delta" label-align="right" align="right">
          {{ formartFormP2WithUseGrouping(props.result.delta) }}
        </el-descriptions-item>
        <el-descriptions-item label="deltacash" label-align="right" align="right">
          {{ formartFormP2WithUseGrouping(props.result.deltacash) }}
        </el-descriptions-item>
        <el-descriptions-item label="gamma" label-align="right" align="right">
          {{ formartFormP2WithUseGrouping(props.result.gamma) }}
        </el-descriptions-item>
        <el-descriptions-item label="gammacash" label-align="right" align="right">
          {{ formartFormP2WithUseGrouping(props.result.gammacash) }}
        </el-descriptions-item>
        <el-descriptions-item label="vega" label-align="right" align="right">
          {{ formartFormP2WithUseGrouping(props.result.vega) }}
        </el-descriptions-item>
        <el-descriptions-item label="theta" label-align="right" align="right">
          {{ formartFormP2WithUseGrouping(props.result.theta) }}
        </el-descriptions-item>
        <el-descriptions-item label="rho" label-align="right" align="right">
          {{ formartFormP2WithUseGrouping(props.result.rho) }}
        </el-descriptions-item>
        <el-descriptions-item label="标的价格" label-align="right" align="right">
          {{ formartFormP2WithUseGrouping(props.result.spotPrice) }}
        </el-descriptions-item>
        <el-descriptions-item label="无风险利率" label-align="right" align="right">
          {{ formartTableWithP3Symbol(props.result.dscRate) }}
        </el-descriptions-item>
        <el-descriptions-item label="波动率" label-align="right" align="right">
          {{ formartTableWithP3Symbol(props.result.volRate) }}
        </el-descriptions-item>
        <el-descriptions-item label-class-name=" " label="" label-align="right" align="right">

        </el-descriptions-item>
      </el-descriptions>
    </div>
    <div class="optionst04" style="position:fixed;left:-2000px;z-index=-1;" ref="exportRef">
      <el-descriptions :column="data.column" border>
        <el-descriptions-item
            v-for="item in Object.keys(props.result).filter(item=>[ '观察方式','行权方式','敲出方向','观察频率','期权单价','收益金额','执行价上限','执行价下限','高行权价','低行权价','高收益金额','中收益金额','低收益金额','标的', '交易日期', '合约类型', '合约交易方向', '到期日', '执行价', '数量', '名义金额', '开仓标的价', '期权单价'].includes(item))"
            :label="item" label-align="right" align="right">
          {{ props.result[item] }}
        </el-descriptions-item>
        <el-descriptions-item
            v-for="item in Object.keys(props.result).filter(item=>[ '区间内收益率','区间外收益率','障碍价比例','敲出补偿比例','保底收益率'].includes(item))"
            :label="item" label-align="right" align="right">
          {{ props.result[item] }}%
        </el-descriptions-item>
        <el-descriptions-item
            v-for="item in Object.keys(props.result).filter(item=>[ '百分比估值','npv'].includes(item))"
            :label="item" label-align="right" align="right">
          {{ formartFormP2(props.result[item]) }}
        </el-descriptions-item>
      </el-descriptions>
    </div>
  </div>
</template>

<script setup name="single">
import html2canvas from 'html2canvas'
import InputAmount from '../../../../xquant/base/InputAmount'
import Numberinput from '../../../../xquant/base/number'
import {computed, getCurrentInstance, inject, nextTick, onMounted, reactive, ref, toRefs, watch} from 'vue'
import {getInstrumentList} from '@/api/calc/otcOption/calc'
import { CalcNpvByNpvPercent , CalcNpvPercentByNpv } from '@/views/calc/otcOtion/instrument/common/common'
import {formartTableWithP2Symbol, formartTableWithP3Symbol, formartFormP2,formartFormP2WithUseGrouping,formartFormP4, formatAmount} from '@/utils/numberUtil'


const {proxy} = getCurrentInstance()
const dialogVisible = ref(false)
const activeName = ref('first')

const handleClick = (tab, event) => {
}
const props = defineProps({
  calcInvert: {
    type: Boolean,
    default: false
  },
  calcMarketNpv: {
    type: Boolean,
    default: false
  },
  result: {
    type: Object,
    default: {}
  }
})
const data = reactive({
  column: 2,
  newNpv: '',
  showSwitch: false,
  showNpvInput: false,
  yearnpvPercentage: '',
  npvPercentage: ''
})
const showSwitch = toRefs(data)

watch(() => props.result, (nv, ov) => {
  data.column = 2
  //判断props.result是否为空
  if (Object.keys(nv).length === 0) {
    data.column = 2
    return
  }
  if(props.result.npv){
    data.newNpv = props.result.npv
    data.npvPercentage = props.result['npvPercentage']
    data.yearnpvPercentage = props.result['yearnpvPercentage']
  }
  nextTick(() => {
    if (proxy.$refs.resultRef.childNodes[0].childNodes[1].childNodes[0].clientWidth > 350) {
      data.column = 1
    } else {
      data.column = 2
    }
  })
}, {
  deep: true,
  immediate: true
})

const getNewNpv = () => {
  return data.newNpv
}

const getData = () => {
  return data
}
const exportImage = () => {
  //如果proxy.$refs.result为空，则不导出
  if (!proxy.$refs.exportRef) {
    return
  }

  html2canvas(proxy.$refs.exportRef).then(canvas => {
    const url = canvas.toDataURL()
    proxy.$saveAs(url, `${props.result['type']}期权试定价结果.jpg`)
  })
}
const exportSimpleTxtFile = () => {
  let textContent = ''
  //如果props.result为空，则不执行
  if (Object.keys(props.result).length === 0) {
    return
  }
  let keys = Object.keys(props.result)
  textContent = `${props.result['标的']}@${props.result.spotPrice}, ${props.result['到期日']}, ${props.result['执行价']},${props.result['合约类型']=='P'?'Put':'Call'},  ${props.result['合约交易方向']}￥${formartFormP2(props.result['npv'])}, ${formartFormP2(props.result['npvPercentage'] )}%`
  // 标的@名义本金，到期日,执行价期权类型（看涨看跌），客户卖价￥百分比估值
  // v2205.DCE@8,510.00， 2022/3/7， 8,810.00Call， 客户卖价￥60.50， 0.71%
  return textContent
  // const blob = new Blob([textContent], {type: 'application/json'})
  // proxy.$saveAs(blob, `${props.result['type']}期权试定价结果简明式导出.txt`)
}

const getIndex = inject('getIndex')
const getIndexRef = inject('getIndexRef')
const exportTxtFile =  () => {
  let textContent = ''
  textContent+=`腿号：${ getIndex( proxy.$attrs.index)} \r\n`
  let indexRef = getIndexRef(proxy.$attrs.index)
  let unit = ''
  if (indexRef[0].proxy){
     unit = indexRef[0].proxy.$refs['underlyerIdRef'].underlyerIdsList[0].unit
  }
  //如果props.result为空，则不执行
  if (Object.keys(props.result).length === 0) {
    return
  }
  let keys = Object.keys(props.result)
  keys.forEach(key => {
    if (['观察方式', '行权方式', '区间内收益率', '区间外收益率', '障碍价比例', '敲出补偿比例', '保底收益率', '敲出方向', '观察频率', '期权单价', '百分比期权费', '执行价上限', '收益金额', '执行价下限', '高行权价', '低行权价', '高收益金额', '中收益金额', '低收益金额', '标的', '交易日期', '合约类型', '合约交易方向', '到期日', '执行价', '数量', '名义金额', '开仓标的价', '期权单价'/*, '百分比估值'*/].includes(key)) {
      if ('名义金额'==key && unit!=null) {
        textContent += `交易单位: ${unit} \r\n`
      }
      if (['区间内收益率', '区间外收益率', '障碍价比例', '敲出补偿比例', '保底收益率'].includes(key)) {
        textContent += `${key}: ${props.result[key]}% \r\n`
      }else {
        textContent += `${key}: ${props.result[key]} \r\n`
      }
    }
  })
  keys.forEach(key => {
    if (['npv'].includes(key)) {
      textContent += `金额:` + formartFormP2(props.result[key]) + ` \r\n`
    }
  })

  return textContent.toString()
  // const blob = new Blob([textContent], {type: 'application/json'})
  // proxy.$saveAs(blob, `${props.result['type']}期权试定价结果详细式导出.txt`)
}

const openTxtDialog = () => {
  dialogVisible.value = true
}
defineExpose(
    {
      getNewNpv,
      getData
    }
)
</script>

<style scoped>
/deep/ .el-input__inner {
  text-align: end;
}
</style>
